package com.chang.rentmall.servicesImpl;

import com.chang.rentmall.beans.BaseBean;
import com.chang.rentmall.beans.MessageBean;
import com.chang.rentmall.beans.ShopTypeBean;
import com.chang.rentmall.daos.ShopTypeDao;
import com.chang.rentmall.services.ShopTypeService;
import com.chang.rentmall.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShopTypeServiceImpl implements ShopTypeService {
    @Autowired
    ShopTypeDao shopTypeDao;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public MessageBean addShopType(BaseBean<ShopTypeBean> baseBean) {
        MessageBean messageBean = new MessageBean();
        ShopTypeBean shopTypeBean = baseBean.getForm();
        String nowTime = Utils.getLocalDateTime();
        shopTypeBean.setCreateTime(nowTime);
        int flag = shopTypeDao.addShopType(baseBean.getForm());
        if (flag > 0) {
            logger.info("添加店铺类型： " + baseBean.getForm().getTitle() + "  成功   -- 创建时间: " + nowTime);
            messageBean.setValues(200, "操作成功", "");
        } else {
            logger.info("添加店铺类型： " + baseBean.getForm().getTitle() + "  失败   -- 创建时间: " + nowTime);
            messageBean.setValues(-1, "添加失败", "");
        }

        return messageBean;
    }

    @Override
    public MessageBean deleteSopType(BaseBean<ShopTypeBean> baseBean) {
        MessageBean messageBean = new MessageBean();
        int flag = shopTypeDao.deleteShopType(baseBean.getQuery().getId());
        if (flag == 1) {
            messageBean.setValues(200, "操作成功", "");
        } else {
            messageBean.setValues(-1, "删除失败", "");
        }
        return messageBean;
    }

    @Override
    public MessageBean getShopTypes(BaseBean<ShopTypeBean> baseBean) {
        MessageBean messageBean = new MessageBean();
        List<ShopTypeBean> list = shopTypeDao.getShopTypes();
        List<ShopTypeBean> filtedList = new ArrayList<ShopTypeBean>();
        // 数组二维化
        for (ShopTypeBean typeBean : list) {
            if (typeBean.getParentId() == 0) {
                List<ShopTypeBean> emptyList = new ArrayList<ShopTypeBean>();
                for (ShopTypeBean subTypeBean : list) {
                    if (subTypeBean.getParentId() == typeBean.getId()) {
                        emptyList.add(subTypeBean);
                    }
                }
                typeBean.setList(emptyList);
                filtedList.add(typeBean);
            }
        }
        messageBean.setValues(200, "获取数据成功", filtedList);
        return messageBean;
    }
}
